package com.example.mqttledmenu;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.ListFragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class FragmentHome extends ListFragment {

    private ListView lv;
    private SimpleAdapter adapter;
    private View rootView;
    private EditText keywords;
    private ImageView search_submit;
    private String keyContents = "";
    ArrayList<NewsItem> newsList = new ArrayList<>();

    public void getALLNewsList(String keyContents) {
        newsList = new ArrayList<>();
        if (keyContents.equals("")) {
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
            UploadService uploadService = retrofit.create(UploadService.class);
            Call<ResponseBody> call = uploadService.getnews("");//与后端约定，不传入id直接获取全部
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String result = null;
                    try {
                        result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(getActivity(), "服务端错误~", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        try {
                            JSONArray myjsonArray = new JSONArray(returnData.get("data").toString());
                            for (int i = 0; i < myjsonArray.length(); i++) {
                                JSONObject jsonObject = myjsonArray.getJSONObject(i);
                                newsList.add(new NewsItem(jsonObject.get("authorAvatar").toString().replace("\"", ""),
                                        (String) jsonObject.get("newsAuthor"), (String) jsonObject.get("newsDepartment"),
                                        (String) jsonObject.get("newsTitle"), (String) jsonObject.get("newsContent"), (String) jsonObject.get("newsPublishTime"),
                                        jsonObject.get("newsId").toString(), 1));
                            }
                            adapter = new SimpleAdapter(getActivity(), getData(newsList),
                                    R.layout.news_adapter_item, new String[]{"avatar", "publisher", "title", "brief", "time"},
                                    new int[]{R.id.avatar, R.id.publisher, R.id.title, R.id.brief, R.id.time});
                            //设置glide占位符
                            RequestOptions requestOptions = new RequestOptions()
                                    .placeholder(R.drawable.loading)
                                    .error(R.drawable.unknow_person)
                                    .fallback(R.drawable.unknow_person);
                            //设置头像切换效果(其实比较耗性能)
                            DrawableCrossFadeFactory factory = new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
                            adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                                @Override
                                public boolean setViewValue(View view, Object data, String textRepresentation) {
                                    if (view instanceof ImageView) {
                                        ImageView iv = (ImageView) view;
                                        Glide.with(FragmentHome.this)
                                                .load(data.toString())
                                                .apply(requestOptions)
                                                .transition(DrawableTransitionOptions.with(factory)).transform(new CircleCrop()).into(iv);
                                        return true;
                                    }
                                    if (view.getId() == R.id.brief) {
                                        TextView tv = (TextView) view;
                                        String str = data.toString();
                                        if (str.length() > 18) {
                                            tv.setText(str.substring(0, 16) + "...");
                                            return true;
                                        }
                                    }
                                    return false;
                                }
                            });
                            setListAdapter(adapter);
                        } catch (JSONException e) {
                            Log.d("nightowl", "onResponse: 接口调用异常~");
                            e.printStackTrace();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } else {
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
            UploadService uploadService = retrofit.create(UploadService.class);
            Call<ResponseBody> call = uploadService.searchKey(keyContents);//与后端约定，不传入id直接获取全部
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String result = null;
                    try {
                        result = response.body().string();
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(getActivity(), "服务端错误~", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        try {
                            JSONArray myjsonArray = new JSONArray(returnData.get("data").toString());
                            for (int i = 0; i < myjsonArray.length(); i++) {
                                JSONObject jsonObject = myjsonArray.getJSONObject(i);
                                newsList.add(new NewsItem(jsonObject.get("authorAvatar").toString().replace("\"", ""),
                                        (String) jsonObject.get("newsAuthor"), (String) jsonObject.get("newsDepartment"),
                                        (String) jsonObject.get("newsTitle"), (String) jsonObject.get("newsContent"), (String) jsonObject.get("newsPublishTime"),
                                        jsonObject.get("newsId").toString(), 1));
                            }
                            adapter = new SimpleAdapter(getActivity(), getData(newsList),
                                    R.layout.news_adapter_item, new String[]{"avatar", "publisher", "title", "brief", "time"},
                                    new int[]{R.id.avatar, R.id.publisher, R.id.title, R.id.brief, R.id.time});
                            //设置glide占位符
                            RequestOptions requestOptions = new RequestOptions()
                                    .placeholder(R.drawable.loading)
                                    .error(R.drawable.unknow_person)
                                    .fallback(R.drawable.unknow_person);
                            //设置头像切换效果(其实比较耗性能)
                            DrawableCrossFadeFactory factory = new DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build();
                            adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                                @Override
                                public boolean setViewValue(View view, Object data, String textRepresentation) {
                                    if (view instanceof ImageView) {
                                        ImageView iv = (ImageView) view;
                                        Glide.with(FragmentHome.this)
                                                .load(data.toString())
                                                .apply(requestOptions)
                                                .transition(DrawableTransitionOptions.with(factory)).transform(new CircleCrop()).into(iv);
                                        return true;
                                    }
                                    if (view.getId() == R.id.brief) {
                                        TextView tv = (TextView) view;
                                        String str = data.toString();
                                        if (str.length() > 18) {
                                            tv.setText(str.substring(0, 16) + "...");
                                            return true;
                                        }
                                    }
                                    return false;
                                }
                            });
                            setListAdapter(adapter);
                        } catch (JSONException e) {
                            Log.d("nightowl", "onResponse: 接口调用异常~");
                            e.printStackTrace();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getALLNewsList("");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home, container, false);
        }
        initView();
        return rootView;
    }

    //监听点击事件
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        //跳转到详情页,传递新闻id参数
        Intent intent = new Intent();
        intent.setClass(getActivity(), DetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("news_id", newsList.get(position).news_id);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    //对数据进行加载
    private List<? extends Map<String, ?>> getData(ArrayList<NewsItem> newsList) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (NewsItem item : newsList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("avatar", item.avatar);
            map.put("publisher", item.publisher);
            map.put("title", item.title);
            map.put("brief", item.brief);
            map.put("time", item.time);
            list.add(map);
        }
        return list;
    }

    private void initView() {
        lv = rootView.findViewById(android.R.id.list);
        search_submit = rootView.findViewById(R.id.search_btn);
        search_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keywords = rootView.findViewById(R.id.search_key);
                keyContents = keywords.getText().toString();
                getALLNewsList(keyContents);
            }
        });
    }
}